<?php
namespace app\admin\controller;
use app\common\model\OrdersItem;
use app\common\model\Express;
use think\Validate;
use think\Db;
use think\Session;

class ExpressController extends BaseController
{
    public function lists()
    {
        return view();
    }
    public function getList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['express_no'])) {
            $where['express_no'] = ['like', $where['express_no'] . '%'];
        }
        
        if (!empty($where['date1']) && !empty($where['date2'])) {
            $date1 = strtotime($where['date1']);
            $date2 = strtotime($where['date2']) + 24*60*60;
            unset($where['date1']);
            unset($where['date2']);
            $where['add_time'] = ['between',[$date1, $date2]];
        }
        
        
        $page = max(input('get.page',0),1);
        $page_size = 10;
         // 获取团队 
         $account_id = Session::get('uid');
         $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
         if(!empty($account_member)){
             $organization_list = array_map(function($item){
                 return $item['organization_id'];
             },collection($account_member)->toArray());
             $where['organization_id'] = ['in',$organization_list];
         }
        $total = Express::where($where)->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('ok','',$data);
        }
        $exp_rows = Express::with('items,acctInfo')
                            ->where($where)
                            ->order('add_time desc')
                            ->page($page,$page_size)           
                            ->select()->toArray();
        //return $exp_rows;
        //商品信息
        $order_item_ids = [];
        foreach ($exp_rows as $row) {
            foreach ($row['items'] as $item) {
                $order_item_ids[] = $item['order_item_id'];
            }
        }
        $order_items = OrdersItem::where('id', 'in', $order_item_ids)
                                ->with('goodsInfo')->select()->toArray();
        //map结构
        $order_items_map = [];
        foreach ($order_items as $item) {
            $order_items_map[$item['id']] = $item;
        }
        //return $order_items_map;
        $rows = [];
        foreach ($exp_rows as $exp) {
            $info = [
                'id'            => $exp['id'],
                'name'          => $exp['name'],
                'express_no'    => $exp['express_no'],
                'sender'        => $exp['acct_info']['true_name'],
                'add_day'       => date('Y-m-d', $exp['add_time']),
                'add_time'      => date('H:i', $exp['add_time']),
            ];
            $info['items'] = [];
            foreach ($exp['items'] as $item) {
                $order_item = $order_items_map[$item['order_item_id']];
                $tmp = [
                    'goods_name'=> $order_item['goods_info']['name'],
                    'goods_pic' => config('upload_path') . $order_item['goods_info']['picture']
                ];
                $info['items'][] = $tmp;
            }
            
            $rows[] = $info;

        }
        $data['rows'] = $rows;
        $this->success('获取成功','',$data);
    }
    public function handle()
    {
        $data = input('post.');
        //return $data;
        $info = [
            'name'          => $data['name'],
            'express_no'    => $data['express_no'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ];
        $validate = new Validate([
            ['name','require','请选择快递公司'],
            ['express_no','require','快递单号必需'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        //判断重复
        if ($this->isRepeated($info['name'], $info['express_no'])) {
            $this->error('快递单号已存在');
        } 
        //不同订单号不能一起发
        if ($this->isDiff(array_column($data['items'], 'order_item_id'))) {
            $this->error('订单号不一致');
        }

        //数据验证
        $validate = new Validate([
            ['order_item_id','require','error1'],
            ['exp_qty','require|number|gt:0','数量必需|数量必须是数值|数量不能为 0'],
        ]);
        foreach ($data['items'] as $item) {
            if (!$validate->check($item)) {
                $this->error($validate->getError());
            }
            //数量判断,不能多发
            $recv_qty = Db::name('stock_in')->where('id',$item['id'])->value('qty');
            $send_qty = Db::name('express_item')->where('stock_in_id',$item['id'])->sum('qty');
            if ($send_qty + $item['exp_qty']>$recv_qty) {
                $this->error('发货超出了到货数量');
            }

        }
        // 获取记录团队发货 
        // $account_id = Session::get('uid');
        // $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        // if(!empty($account_member)){
        //     $account_member_count = count($account_member);
        //     if($account_member_count == 1){//单团队
        //         $info['organization_id'] = $account_member[0]['organization_id'];
        //     }else{//多团队
        //         $this->error('多团队不能发货');
        //     }
        // }
        if(isset($data['items'][0]['organization_id'])){
            $info['organization_id'] = $data['items'][0]['organization_id'];
        }

        $express_id = Db::name('express')->insertGetId($info);
        $affected = 0;
        foreach ($data['items'] as $item) {
            $row = [
                'express_id'    => $express_id,
                'order_item_id' => $item['order_item_id'],
                'qty'           => $item['exp_qty'],
                'remarks'       => $item['exp_remarks'],
                'stock_in_id'   => $item['id']
            ];
            
            $affected += Db::name('express_item')->insert($row);
        }
        $oi_model = new OrdersItem;
        if ( $affected == count($data['items']) ) {
            foreach ($data['items'] as $item) {
                //更新订单状态
                $oi_model->updateProgress($item['order_item_id']);
                //更新stock状态
                $recv_qty = Db::name('stock_in')->where('id',$item['id'])->sum('qty');
                $send_qty = Db::name('express_item')->where('stock_in_id',$item['id'])->sum('qty');
                if ($send_qty == $recv_qty) {
                    Db::name('stock_in')->where('id', $item['id'])->update(['status'=>2]);
                }
            }
            $this->success('操作成功');
        } else {
            $this->error('添加失败: 02');
        }
    }
    public function handle2()
    {
        $data = input('post.');
        //return $data;
        $validate = new Validate([
            ['name','require','请选择快递公司'],
            ['exp_no','require','快递单号必需'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //判断重复
        if ($this->isRepeated($data['name'], $data['exp_no'])) {
            $this->error('快递单号已存在');
        }
        
        //数据验证
        $validate = new Validate([
            ['order_item_id','require','error1'],
            ['qty','require|number|gt:0','数量必需|数量必须是数值|数量不能 < 1'],
        ]);
        foreach ($data['items'] as $key => $item) {
            if (!$validate->check($item)) {
                $this->error($validate->getError());
            }
            //数量判断,不能多发
            if ($this->isOverflow($item['order_item_id'], $item['qty'])) {
                $this->error('库存不足：序号' . ($key+1));
            }
        }
        //主表添加
        $info = [
            'name'          => $data['name'],
            'express_no'    => $data['exp_no'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ];
        $express_id = Db::name('express')->insertGetId($info);
        //添加明细
        $affected = 0;
        $oi_model = new OrdersItem;
        foreach ($data['items'] as $item) {
            $row = [
                'express_id'    => $express_id,
                'order_item_id' => $item['order_item_id'],
                'qty'           => $item['qty'],
                'remarks'       => $item['remarks']
            ];
            $affected += Db::name('express_item')->insert($row);

            //更新订单状态
            $oi_model->updateProgress($item['order_item_id']);
            //更新stock状态
            $where = [
                'order_item_id' => $item['order_item_id']
            ];
            $recv_qty = Db::name('stock_in')->where($where)->sum('qty');
            $send_qty = Db::name('express_item')->where($where)->sum('qty');
            if ($send_qty == $recv_qty) {
                Db::name('stock_in')->where($where)->update(['status'=>2]);
            }
        }

        if ( $affected == count($data['items']) ) {
            $this->success('操作成功');
        } else {
            $this->error('添加失败');
        }
    }
    protected function isRepeated($name, $exp_no)
    {
        return boolval(Db::name('express')->where(['name' => $name, 'express_no' => $exp_no])->find());
    }
    protected function isDiff(array $oi_ids)
    {
        $rows = Db::name('orders_item')->where('id', 'in', $oi_ids)->field('distinct order_id')->select();
        return count($rows) > 1 ? true : false;
    }
    protected function isOverflow($order_item_id, $qty)
    {
        $where['order_item_id'] = $order_item_id;

        $recv_qty = Db::name('stock_in')->where($where)->sum('qty');
        $send_qty = Db::name('express_item')->where($where)->sum('qty');

        if ($send_qty + $qty > $recv_qty) {
            return true;
        } else {
             return false;
        }
    }
    public function changeExpHandle()
    {
        $data = input('post.');
        //return $data;
        $validate = new Validate([
            ['name','require','请选择快递公司'],
            ['express_no','require','快递单号必需'],
            ['order_item_id','require','error1'],
            ['id','require','error2'],
            ['qty','require|number|gt:0','数量必需|数量必须是数值|数量不能为 0'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //判断单号是否存在
        $where = [
            'name'          => $data['name'],
            'express_no'    => $data['express_no']
        ];
        $exp = Db::name('express')->where($where)->find();
        if ($exp){
            $this->error('快递单号已存在');
        }
        //数量是否一致
        $chg_qty = Db::name('orders_item_change')->where('id',$data['id'])->value('qty');
        if ($chg_qty != $data['qty']) {
            $this->error('发货数量与换货数量不一致');
        }
        
        $info = [
            'name'          => $data['name'],
            'express_no'    => $data['express_no'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ];
        // 获取记录团队发货 
        // $account_id = Session::get('uid');
        // $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        // if(!empty($account_member)){
        //     $account_member_count = count($account_member);
        //     if($account_member_count == 1){//单团队
        //         $info['organization_id'] = $account_member[0]['organization_id'];
        //     }else{//多团队
        //         $this->error('多团队不能发货');
        //     }
        // }
        $order = Db::name('orders')->where('order_no',$data['order_no'])->find();
        if(isset($order['organization_id'])){
            $info['organization_id'] = $order['organization_id'];
        }
        if (!Db::name('express')->insert($info)) {
            $this->error('添加失败: 01');
        }
        $data['express_id'] = Db::name('express')->where($where)->value('id');
        
        $row = [
            'express_id'        => $data['express_id'],
            'order_item_id'     => $data['order_item_id'],
            'qty'               => $data['qty']
        ];
        Db::name('express_item')->insert($row);
        Db::name('orders_item_change')->where('id',$data['id'])
                                    ->update(['exp_name'=>$data['name'],'exp_no'=>$data['express_no']]);
        $this->success('添加成功');
    }
    /**
     * 退货登记物流
     */
    public function returnExpHandle()
    {
        $data = input('post.');
        $validate = new Validate([
            ['name','require','请选择快递公司'],
            ['express_no','require','快递单号必需'],
            ['order_item_id','require','error1'],
            ['id','require','error2'],
            ['qty','require|number|gt:0','数量必需|数量必须是数值|数量不能为 0'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //数量是否一致
        $chg_qty = Db::name('orders_item_reject')->where('id',$data['id'])->value('qty');
        if ($chg_qty != $data['qty']) {
            $this->error('发货数量与退货数量不一致');
        }
        
        Db::name('orders_item_reject')->where('id',$data['id'])
                                    ->update(['exp_name'=>$data['name'],'exp_no'=>$data['express_no']]);
        $this->success('添加成功');
    }
    /**
     * 修改物流
     */
    public function editExpress()
    {
        $data = input('post.');
        $validate = new Validate([
            ['name','require','请选择快递公司'],
            ['id','require','error2'],
            ['express_no','require','快递单号必需']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        Db::name('express')->where('id',$data['id'])
                                    ->update(['name'=>$data['name'],'express_no'=>$data['express_no']]);
        $this->success('修改成功');
    }
}